from flask import render_template, request, jsonify
from . import plant_bp
from ..utils.stats import record_api_call
import requests
import base64
import json
from ..utils.baidu_ai import get_access_token

@plant_bp.route('/')
def index():
    return render_template('modules/plant_recognition.html')

@plant_bp.route('/process', methods=['POST'])
def process():
    # 记录API调用
    record_api_call('plant')
    
    try:
        # 获取access_token
        access_token = get_access_token()
        if not access_token:
            return jsonify({
                'success': False,
                'message': '获取access_token失败'
            })

        # 处理图片数据
        if 'image' not in request.files:
            return jsonify({
                'success': False,
                'message': '没有上传图片'
            })
            
        image = request.files['image'].read()
        image_base64 = base64.b64encode(image).decode('utf-8')
        
        # 准备请求参数
        params = {
            'image': image_base64,
            'baike_num': request.form.get('baike_num', '1')
        }
        
        # 调用百度API
        url = f'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token={access_token}'
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(url, data=params, headers=headers)
        
        # 处理响应
        if response.status_code == 200:
            result = response.json()
            if 'error_code' in result:
                return jsonify({
                    'success': False,
                    'message': f"API错误: {result.get('error_msg', '未知错误')}"
                })
            
            # 确保返回的数据格式正确    
            return jsonify({
                'success': True,
                'result': {
                    'result': result.get('result', [])  # 确保result字段存在
                }
            })
        else:
            return jsonify({
                'success': False,
                'message': f'API请求失败: {response.status_code}'
            })
            
    except Exception as e:
        print(f"Error processing image: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'处理图片时发生错误: {str(e)}'
        }) 